package com.zcl.entity;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.DelayQueue;

/**
 * .
 *
 * @Author Chenglin Zhu
 * @Date 2021/6/25 11:16
 */
public class DelayedTest {

    // 自动取消线程开关
    static boolean flag = true;
    //存放过期订单
    static DelayQueue<Order> queue = new DelayQueue();

    public static void main(String[] args) {
        DelayedTest delayedTest = new DelayedTest();
        //新建一个线程，用来模拟定时取消订单job
        new Thread(() -> {
            System.out.println("开启自动取消订单job,当前时间：" + DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATETIME_PATTERN));
            while (flag) {
                try {
                    Order order = delayedTest.queue.take();
                    order.setOrderStatus("超时取消");
                    System.out.println("订单：" + order.getOrderNO() + "超时取消" + DateUtil.format(LocalDateTime.now(), DatePattern.NORM_DATETIME_PATTERN));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(() -> {
            //定义最早的订单的创建时间
            long now = System.currentTimeMillis();
            System.out.println("下单开始时间" + DateUtil.format(new Date(now), DatePattern.NORM_DATETIME_PATTERN));
            //下面模拟6个订单，每个订单的创建时间依次延后3秒
            queue.add(new Order("001", new Date(now + 3000), "未支付"));
            queue.add(new Order("002", new Date(now + 6000), "未支付"));
            queue.add(new Order("003", new Date(now + 9000), "未支付"));
            queue.add(new Order("004", new Date(now + 12000), "未支付"));
        }).start();
    }
}
